#pragma once

#include "WHttpClientCommon.h"
#include <openssl/ssl.h>
#include <openssl/err.h>

class WSyncHttpClient {
public:
    WSyncHttpClient();
    ~WSyncHttpClient();

    // 发送 HTTP 请求并接收响应，目前这个只是普通消息处理，若想上传和下载文件，需要额外添加接口处理
    std::shared_ptr<HttpClientRspMsg> sendRequest(const std::string& url, const HttpClientReqMsg& reqMsg, int timeout = 5);
    // 只支持带content-length的文件下载，不支持chunk流文件下载
    void sendRequestToDwFile(std::string url, const HttpClientReqMsg& reqMsg, HttpClientCbFun cbFun, int timeout = 5);

private:
    struct ConnectionInfo
    {
        int sockfd = -1;
        SSL_CTX* ctx = nullptr;
        SSL* ssl = nullptr;
        int errStatus = 0; // 0表示成功
    };

    // 解析 URL 获取协议、主机、端口和路径
    void parseUrl(const std::string& url, std::string& protocol, std::string& host, int& port, std::string& path) const;

    // 拼接 URL
    std::string buildUrl(const std::string& uri, const std::map<std::string, std::string>& querys) const;

    std::string getIpFromDNS(const std::string &dnsStr, bool isIpv6First = false);

    // 创建 HTTP 请求
    std::string buildHttpRequest(const std::string& host, const HttpClientReqMsg& reqMsg) const;

    // 解析响应头部和主体
    void parseResponse(const std::string& response, std::shared_ptr<HttpClientRspMsg>& rspMsg, bool chunkFlag = false) const;

    // 读取响应数据
    std::string readResponseData(SSL* ssl, int sockfd, const std::string& protocol, size_t contentLength) const;

    ConnectionInfo createConnection(const std::string& host, int port, const std::string& protocol, int timeout);

    int sendHttpRequest(ConnectionInfo& conn, const std::string& protocol, const std::string& host, const HttpClientReqMsg& reqMsg);
};
